package com.moss.system.factory;

import com.moss.common.exception.ServiceException;
import com.moss.system.service.SampleBranchService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SampleFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext context;

    private static final Map<String, SampleBranchService> SAMPLE_MAP = new HashMap<>();


    @Override
    public void afterPropertiesSet() throws Exception {
        context.getBeansOfType(SampleBranchService.class)
                .values()
                .forEach(
                        sample -> SAMPLE_MAP.put(sample.type(),sample)
                );
    }

    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public SampleBranchService create(String type){
        SampleBranchService sampleBranchService = SAMPLE_MAP.get(type);
        if (sampleBranchService == null){
            throw new ServiceException("检测类型不存在，请确认");
        }
        return sampleBranchService;
    }
}
